package com.etone.smartAudit.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etone.smartAudit.domain.Admin;
import com.etone.smartAudit.domain.Tool;
import com.etone.smartAudit.domain.ToolCase;
import com.etone.smartAudit.dto.FileDTO;
import com.etone.smartAudit.dto.tool.ToolDTO;
import com.etone.smartAudit.dto.toolCase.ToolCaseDTO;
import com.etone.smartAudit.enums.StateType;
import com.etone.smartAudit.error.CustomParameterizedException;
import com.etone.smartAudit.mapper.ToolCaseMapper;
import com.etone.smartAudit.mapper.ToolMapper;
import com.etone.smartAudit.mapstruct.ToolMapStruct;
import com.etone.smartAudit.utils.ArraysExtendUtil;
import com.etone.smartAudit.utils.ImageUtil;
import com.etone.smartAudit.vo.FileVO;
import com.etone.smartAudit.vo.PagerVO;
import com.etone.smartAudit.vo.tool.ToolBaseVO;
import com.etone.smartAudit.vo.tool.ToolDetailVO;
import com.etone.smartAudit.vo.tool.ToolVO;
import com.etone.smartAudit.vo.toolCase.ToolCaseVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author: 蒋学伟
 * @create: 2020-07-08 14:42:52
 * @Description 工具管理
 */
@AllArgsConstructor
@Service
public class ToolService extends ServiceImpl<ToolMapper, Tool> {
    private ToolMapper toolMapper;

    private ToolCaseMapper toolCaseMapper;

    private ToolMapStruct toolMapStruct;

    private FileUploadService fileUploadService;

    /**
     * 获取工具列表
     *
     * @param name
     * @param page
     * @param pageSize
     * @return
     */
    public PagerVO<ToolVO> list(String name, int page, int pageSize) {
        Page<ToolVO> toolVOPage = PageHelper.startPage(page, pageSize).doSelectPage(() -> {
            toolMapper.findList(name);
        });
        return PagerVO.of(toolVOPage);
    }

    /**
     * 工具详情
     *
     * @param id
     * @return
     */
    public ToolDetailVO detail(Integer id) {
        Tool tool = get(id);
        return toolMapStruct.getToolDetailVO(tool);
    }

    /**
     * 编辑工具内容
     *
     * @param id
     * @param toolDTO
     */
    @Transactional(rollbackFor = Exception.class)
    public void edit(Integer id, ToolDTO toolDTO) {
        Tool tool = get(id);

        //旧文件
        List<FileVO> oldCover = StringUtils.isEmpty(tool.getCover()) ? null : Arrays.asList(JSON.parseObject(tool.getCover(), FileVO.class));
        List<FileVO> oldFiles = tool.getFiles() == null ? null : JSONArray.parseArray(tool.getFiles(), FileVO.class);
        List<String> oldDetailFiles = StringUtils.isEmpty(tool.getDetail()) ? null : ImageUtil.getImgTagUrl(tool.getDetail());

        BeanUtils.copyProperties(toolDTO, tool);
        tool.setFiles(toolDTO.getFiles() == null ? null : JSONArray.toJSONString(toolDTO.getFiles()));
        tool.setCover(toolDTO.getCover() == null ? null : JSON.toJSONString(toolDTO.getCover()));

        updateById(tool);

        //清理图片
        fileUploadService.deleteFileForUpdate(ArraysExtendUtil.mergerArraysList(toolDTO.getFiles(), Arrays.asList(toolDTO.getCover())), ArraysExtendUtil.mergerArraysList(oldCover, oldFiles));
        fileUploadService.deleteFileForUpdateByURL(StringUtils.isEmpty(toolDTO.getDetail()) ? null : ImageUtil.getImgTagUrl(toolDTO.getDetail()), oldDetailFiles);

    }

    /**
     * 申请次数+1
     *
     * @param ids
     */
    public void addApplyCnt(List<Integer> ids) {
        addApplyCnt(ids, 1);
    }

    /**
     * 申请次数+number
     *
     * @param ids
     */
    public void addApplyCnt(List<Integer> ids, int number) {
        toolMapper.addApplyCnt(ids, number);
    }

    /**
     * 工具基本信息列表
     *
     * @return
     */
    public List<ToolBaseVO> listSimple() {
        return toolMapper.findListSimple();
    }

    public Tool get(Integer id) {
        Tool tool = toolMapper.selectById(id);
        if (tool == null || tool.getState() == null || !tool.getState().equals(StateType.ENABLE)) {
            throw new CustomParameterizedException("工具不存在");
        }
        return tool;
    }

    /**
     * 查找案例
     *
     * @param caseId
     * @return
     */
    public ToolCase getToolCase(Integer caseId) {
        ToolCase toolCase = toolCaseMapper.selectById(caseId);
        if (toolCase == null || toolCase.getState() == null || !toolCase.getState().equals(StateType.ENABLE)) {
            throw new CustomParameterizedException("案例不存在");
        }
        return toolCase;
    }

    /**
     * 工具案例列表
     *
     * @param id
     * @param page
     * @param pageSize
     * @return
     */
    public PagerVO<ToolCaseVO> findCaseList(Integer id, int page, int pageSize) {
        Page<ToolCase> toolCasePage = PageHelper.startPage(page, pageSize).doSelectPage(() -> {
            toolCaseMapper.finList(id);
        });
        List<ToolCaseVO> toolCaseVOs = toolMapStruct.getToolCaseVO(toolCasePage.getResult());

        return PagerVO.of(toolCasePage.getPageNum(), toolCasePage.getPageSize(), toolCasePage.getTotal(), toolCaseVOs);
    }

    /**
     * 添加案例
     *
     * @param toolId
     * @param admin
     * @param toolCaseDTO
     */
    public void addCase(Integer toolId, Admin admin, ToolCaseDTO toolCaseDTO) {
        Tool tool = get(toolId);
        toolCaseMapper.insert(
                ToolCase
                        .builder()
                        .createAdminId(admin.getId())
                        .createAdminNickName(admin.getNickName())
                        .createTime(new Date())
                        .downloadCnt(0)
                        .files(toolCaseDTO.getFiles() == null ? "" : JSON.toJSONString(toolCaseDTO.getFiles()))
                        .cover(toolCaseDTO.getCover() == null ? "" : JSON.toJSONString(toolCaseDTO.getCover()))
                        .name(toolCaseDTO.getName())
                        .remark(toolCaseDTO.getRemark())
                        .state(StateType.ENABLE)
                        .toolId(toolId)
                        .toolName(tool.getName())
                        .build()
        );
        List<FileDTO> files = toolCaseDTO.getFiles();
        fileUploadService.deleteFileByFileDTO(ArraysExtendUtil.mergerArraysList(files, Arrays.asList(toolCaseDTO.getCover())), false, true);
    }

    /**
     * 编辑案例
     *
     * @param toolId
     * @param toolCaseId
     * @param admin
     * @param toolCaseDTO
     */
    public void editCase(Integer toolId, Integer toolCaseId, Admin admin, ToolCaseDTO toolCaseDTO) {
        ToolCase toolCase = getToolCase(toolCaseId);
        if (toolId.intValue() == toolCase.getToolId()) {
            List<FileVO> oldFiles = StringUtils.isEmpty(toolCase.getFiles()) ? null : JSONArray.parseArray(toolCase.getFiles(), FileVO.class);
            toolCase.setName(toolCaseDTO.getName());
            toolCase.setFiles(CollectionUtils.isEmpty(toolCaseDTO.getFiles()) ? null : JSONArray.toJSONString(toolCaseDTO.getFiles()));
            toolCase.setRemark(toolCaseDTO.getRemark());
            updateCase(toolCase);

            fileUploadService.deleteFileForUpdate(toolCaseDTO.getFiles(), oldFiles);
            return;
        }
        throw new CustomParameterizedException("无效案例");
    }

    public void updateCase(ToolCase toolCase) {
        toolCaseMapper.updateById(toolCase);
    }

    /**
     * 下载案例
     *
     * @param id
     * @param caseId
     */
    public void downloadCase(Integer id, Integer caseId) {
        ToolCase toolCase = getToolCase(caseId);
        toolCase.setDownloadCnt(toolCase.getDownloadCnt() == null ? 1 : (toolCase.getDownloadCnt() + 1));
        updateCase(toolCase);
    }

    /**
     * 删除案例
     *
     * @param id
     * @param caseId
     */
    public void deleteCase(Integer id, Integer caseId) {
        ToolCase toolCase = getToolCase(caseId);
        int count = toolCaseMapper.deleteById(caseId);
        if (count <= 0) {
            throw new CustomParameterizedException("案例不存在");
        }
        List<FileVO> fileVOS = StringUtils.isEmpty(toolCase.getFiles()) ? null : JSONArray.parseArray(toolCase.getFiles(), FileVO.class);
        FileVO coverVO = toolCase.getCoverFileVO();
        doDeleteCaseAfter(caseId, ArraysExtendUtil.mergerArraysList(Arrays.asList(coverVO), fileVOS));
    }

    /**
     * 删除案例后的操作
     *
     * @param caseId
     * @param fileVOS
     */
    private void doDeleteCaseAfter(Integer caseId, List<FileVO> fileVOS) {

        //删除文件
        if (!CollectionUtils.isEmpty(fileVOS)) {
            fileUploadService.deleteFileByFileVO(fileVOS, true, false);
        }
    }
}
